package com.rao.gmall.product.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rao.gmall.model.product.SpuImage;
import com.rao.gmall.model.product.SpuInfo;
import com.rao.gmall.model.product.SpuSaleAttr;
import com.rao.gmall.model.product.SpuSaleAttrValue;
import com.rao.gmall.product.mapper.*;
import com.rao.gmall.product.service.SpuInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author nzmxfan
 * @create 2021-08-05-16:32
 */
@Service
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoMapper, SpuInfo> implements SpuInfoService {

    @Resource
    SpuInfoMapper spuInfoMapper;

    @Resource
    SpuImageMapper spuImageMapper;

    @Resource
    SpuSaleAttrMapper spuSaleAttrMapper;

    @Resource
    SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        // 将基础信息保存到 spu_info 中
        spuInfoMapper.insert(spuInfo);
        // 获取 spu_id 属性值
        Long id = spuInfo.getId();

        // spuImageList 存入到 spu_image 表、spu_id 也需要
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)){
            for (SpuImage spuImage : spuImageList) {
                // 设置 spu_id 属性值
                spuImage.setSpuId(id);
                spuImageMapper.insert(spuImage);
            }
        }

        // spuSaleAttrList 存入 spu_sale_attr_value 表中
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
            // 设置 spu_id 属性值
            spuSaleAttr.setSpuId(id);
            spuSaleAttrMapper.insert(spuSaleAttr);
            String saleAttrName = spuSaleAttr.getSaleAttrName();


            // spuSaleAttrValueList 写入 spu_sale_attr_value
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
            for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                // 设置 spu_id 属性值
                spuSaleAttrValue.setSpuId(id);
                spuSaleAttrValue.setSaleAttrName(saleAttrName);
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            }
        }
    }
}
